package com.email;

import lombok.Builder;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import javax.mail.MessagingException;
import java.util.Date;

/**
 * 通用邮件服务
 *
 * @author 大忽悠
 * @create 2022/11/16 18:16
 */
@Data
public class CommonEmailService {
    private final JavaMailSenderImpl javaMailSender;

    @Value("${spring.mail.username}")
    private String sendMailer;

    public CommonEmailService(JavaMailSenderImpl javaMailSender) {
        this.javaMailSender = javaMailSender;
    }

    /**
     * 发送纯文本邮件
     *
     * @param to
     * @param subject
     * @param text
     */
    public void sendTextMailMessage(String subject, String text, String... to) {
            SimpleMailMessage simpleMimeMessage = new SimpleMailMessage();
            //邮件发信人
            simpleMimeMessage.setFrom(sendMailer);
            //邮件收信人  1或多个
            simpleMimeMessage.setTo(to);
            //邮件主题
            simpleMimeMessage.setSubject(subject);
            //邮件内容
            simpleMimeMessage.setText(text);
            //邮件发送时间
            simpleMimeMessage.setSentDate(new Date());

            //发送邮件
            javaMailSender.send(simpleMimeMessage);
    }

    /**
     * 发送复杂邮件
     */
    public void sendComplexMailMessage(String subject, String text, String attachFileName, InputStreamResource inputStreamResource, String... to) {
        try {
            //true 代表支持复杂的类型
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(javaMailSender.createMimeMessage(),true);
            //邮件发信人
            mimeMessageHelper.setFrom(sendMailer);
            //邮件收信人  1或多个
            mimeMessageHelper.setTo(to);
            //邮件主题
            mimeMessageHelper.setSubject(subject);
            //邮件内容
            mimeMessageHelper.setText(text);
            //邮件发送时间
            mimeMessageHelper.setSentDate(new Date());
            //附件
            mimeMessageHelper.addAttachment(attachFileName,inputStreamResource);

            //发送邮件
            javaMailSender.send(mimeMessageHelper.getMimeMessage());
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}
